<?php

namespace app\api\command;
use app\common\model\User;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class Commission extends Command
{
    protected function configure()
    {
        $this->setName('commission')->setHelp('佣金结算')->setDescription('佣金结算');

    }

    protected function execute(Input $input, Output $output)
    {
        $data = db('user_commission')->where('settlement_time','<',time())->where('status',1)->select();
        if($data){
            $userModel  = new User();
            $orderModel = new \app\common\model\Order();
            foreach ($data as $k=>$v){
                $orderInfo = $orderModel->where(['id'=>$v['order_id']])->find();
                $userInfo  = $userModel->where(['id'=>$v['user_id']])->find();
                if($orderInfo && $userInfo){
                    if($v['user_id'] == $orderInfo['user_id']){
                        $memo = "直推奖励";
                    }else{
                        $memo = "代理推广奖励";
                    }
                    $userModel->money($v['money'],$v['user_id'],$memo,$v['order_id'],$v['packages_id']);
                    $up['status']          = 2;
                    $up['settlement_time'] = time();
                }else{
                    $up['status']     = 3;
                    $up['errer_time'] = time();
                }
                $r =db('order')->where(['id'=>$v['order_id']])->update(['order_status'=>5,'settlement_time'=>time(),'order_status_text'=>'订单已结算']);
                if($r){
                  $r = db('user_commission')->where(['id'=>$v['id']])->update($up);
                }
            }
            if($r){
                echo "分佣成功";
            }else{
                echo "分佣失败";
            }

        }else{
            echo "无数据";
        }

    }

}
